コード例 #1
0
#pragma warning disable CS0612 // Type or member is obsolete
        public void SerializeDeserialize_EnrollmentTransaction()
        {
            var original = new EnrollmentTransaction()
            {
                Version   = 0x00,
                PublicKey = ECPoint.Infinity,
            };

            FillRandomTx(original);

            var ret   = _serializer.Serialize(original);
            var copy  = _deserializer.Deserialize <Transaction>(ret);
            var copy2 = _deserializer.Deserialize <EnrollmentTransaction>(ret);

            // Check exclusive data

            foreach (var check in new EnrollmentTransaction[] { (EnrollmentTransaction)copy, copy2 })
            {
                CollectionAssert.AreEqual(original.PublicKey.EncodedData, check.PublicKey.EncodedData);
            }

            // Check base data

            EqualTx(original, copy, copy2);
        }
コード例 #2
0
        public async Task Persist_EnrollmentTx_CallsEnrollmentTxPersister()
        {
            var input = new EnrollmentTransaction();
            var enrollmentTxPersisterMock = AutoMockContainer.GetMock <ITransactionPersister <EnrollmentTransaction> >();
            var testee = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);

            enrollmentTxPersisterMock.Verify(m => m.Persist(input));
        }
コード例 #3
0
        public async Task Process_EnrollmentTx_CallsEnrollmentTxProcessor()
        {
            var input = new EnrollmentTransaction();
            var enrollmentTxProcessorMock = AutoMockContainer.GetMock <IProcessor <EnrollmentTransaction> >();
            var testee = AutoMockContainer.Create <TransactionProcessor>();

            await testee.Process(input);

            enrollmentTxProcessorMock.Verify(m => m.Process(input));
        }
コード例 #4
0
ファイル: StateReader.cs プロジェクト: nie341/ETCBlockchain
        protected virtual bool Enrollment_GetPublicKey(ExecutionEngine engine)
        {
            EnrollmentTransaction tx = engine.EvaluationStack.Pop().GetInterface <EnrollmentTransaction>();

            if (tx == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(tx.PublicKey.EncodePoint(true));
            return(true);
        }
コード例 #5
0
        private static bool Enrollment_GetPublicKey(ScriptEngine engine)
        {
            EnrollmentTransaction tx = engine.EvaluationStack.Pop().GetInterface <EnrollmentTransaction>();

            if (tx == null)
            {
                return(false);
            }
            engine.EvaluationStack.Push(tx.PublicKey.EncodePoint(true));
            return(true);
        }
コード例 #6
0
        private void Populate()
        {
            if (dopopulate)
            {
                dopopulate = false;
                if (!OrgId.HasValue || !PeopleId.HasValue)
                {
                    return;
                }
            }
            var i = (from et in DbUtil.Db.EnrollmentTransactions
                     where et.OrganizationId == OrgId && et.PeopleId == PeopleId
                     where et.TransactionTypeId == 5
                     orderby et.TransactionDate descending
                     select new
            {
                et,
                et.Person.Name,
                et.Organization.OrganizationName,
                et.Organization,
                et.SmallGroups,
                ts = DbUtil.Db.ViewTransactionSummaries.SingleOrDefault(
                    ts => ts.RegId == et.TranId && ts.PeopleId == PeopleId && ts.OrganizationId == OrgId)
            }
                     ).FirstOrDefault();

            if (i == null)
            {
                throw new Exception($"missing PrevOrgMember at oid={OrgId}, pid={PeopleId}");
            }

            PrevMember         = i.et;
            TransactionSummary = i.ts;
            this.CopyPropertiesFrom(PrevMember);
            Name = i.Name;

            AmtFee      = i.ts?.IndPaid + i.ts?.IndDue;
            AmtDonation = i.ts?.IndAmt - AmtFee;
            AmtCoupon   = i.ts?.TotCoupon;

            OrgName       = i.OrganizationName;
            Organization  = i.Organization;
            OrgMemMemTags = i.SmallGroups.SplitStr("\n").ToList();
            Setting       = DbUtil.Db.CreateRegistrationSettings(OrgId ?? 0);
        }
コード例 #7
0
        public void Verify_AttributeUsageECDH02()
        {
            var testee = AutoMockContainer.Create <TransactionOperationManager>();

            var transaction = new EnrollmentTransaction
            {
                Attributes = new []
                {
                    new TransactionAttribute
                    {
                        Usage = TransactionAttributeUsage.ECDH02
                    }
                }
            };

            var result = testee.Verify(transaction);

            result.Should().BeFalse();
        }
コード例 #8
0
        public async Task Process_SetValidatorRegisteredToTrue()
        {
            var pubKey = new byte[33];

            pubKey[0] = 0x02;
            var input = new EnrollmentTransaction
            {
                PublicKey = new ECPoint(pubKey)
            };
            var validator = new Validator
            {
                Registered = false
            };
            var repositoryMock = AutoMockContainer.GetMock <IRepository>();

            repositoryMock.Setup(m => m.GetValidator(input.PublicKey)).ReturnsAsync(validator);
            var testee = AutoMockContainer.Create <EnrollmentTransactionProcessor>();

            await testee.Process(input);

            repositoryMock.Verify(m => m.AddValidator(It.Is <Validator>(v => v == validator && v.Registered)));
        }
コード例 #9
0
        private void Persist(Block block)
        {
            const int UnclaimedItemSize = sizeof(ushort) + sizeof(uint);
            MultiValueDictionary <UInt256, ushort> unspents = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(p), out value))
                {
                    value = new byte[0];
                }
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            MultiValueDictionary <UInt256, ushort, uint> unclaimed = new MultiValueDictionary <UInt256, ushort, uint>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(p), out value))
                {
                    value = new byte[0];
                }
                byte[] data = value.ToArray();
                return(Enumerable.Range(0, data.Length / UnclaimedItemSize).ToDictionary(i => data.ToUInt16(i * UnclaimedItemSize), i => data.ToUInt32(i * UnclaimedItemSize + sizeof(ushort))));
            });
            MultiValueDictionary <UInt256, ushort> unspent_votes = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(p), out value))
                {
                    value = new byte[0];
                }
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            Dictionary <UInt256, Fixed8> quantities = new Dictionary <UInt256, Fixed8>();
            WriteBatch batch         = new WriteBatch();
            long       amount_sysfee = GetSysFeeAmount(block.PrevBlock) + (long)block.Transactions.Sum(p => p.SystemFee);

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Header).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim()));
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Height).Add(tx.ToArray()));
                if (tx.Attributes.Any(p => p.Usage == TransactionAttributeUsage.Vote))
                {
                    unspent_votes.AddEmpty(tx.Hash);
                    for (ushort index = 0; index < tx.Outputs.Length; index++)
                    {
                        if (tx.Outputs[index].AssetId == AntShare.Hash)
                        {
                            unspent_votes.Add(tx.Hash, index);
                        }
                    }
                }
                switch (tx.Type)
                {
                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        if (quantities.ContainsKey(result.AssetId))
                        {
                            quantities[result.AssetId] -= result.Amount;
                        }
                        else
                        {
                            quantities.Add(result.AssetId, -result.Amount);
                        }
                    }
                    break;

                case TransactionType.ClaimTransaction:
                    foreach (CoinReference input in ((ClaimTransaction)tx).Claims)
                    {
                        unclaimed.Remove(input.PrevHash, input.PrevIndex);
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(tx.Hash), true);
                }
                break;

                case TransactionType.PublishTransaction:
                {
                    PublishTransaction publish_tx = (PublishTransaction)tx;
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Contract).Add(publish_tx.Code.ScriptHash), publish_tx.Code.ToArray());
                }
                break;
                }
                unspents.AddEmpty(tx.Hash);
                for (ushort index = 0; index < tx.Outputs.Length; index++)
                {
                    unspents.Add(tx.Hash, index);
                }
            }
            foreach (var group in block.Transactions.SelectMany(p => p.Inputs).GroupBy(p => p.PrevHash))
            {
                int         height;
                Transaction tx = GetTransaction(ReadOptions.Default, group.Key, out height);
                foreach (CoinReference input in group)
                {
                    if (input.PrevIndex == 0)
                    {
                        batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(input.PrevHash));
                    }
                    unspents.Remove(input.PrevHash, input.PrevIndex);
                    unspent_votes.Remove(input.PrevHash, input.PrevIndex);
                    if (tx?.Outputs[input.PrevIndex].AssetId == AntShare.Hash)
                    {
                        unclaimed.Add(input.PrevHash, input.PrevIndex, block.Height);
                    }
                }
            }
            foreach (var unspent in unspents)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var spent in unclaimed)
            {
                if (spent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(spent.Key));
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream(spent.Value.Count * UnclaimedItemSize))
                        using (BinaryWriter w = new BinaryWriter(ms))
                        {
                            foreach (var pair in spent.Value)
                            {
                                w.Write(pair.Key);
                                w.Write(pair.Value);
                            }
                            w.Flush();
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(spent.Key), ms.ToArray());
                        }
                }
            }
            foreach (var unspent in unspent_votes)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var quantity in quantities)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_QuantityIssued).Add(quantity.Key), (GetQuantityIssued(quantity.Key) + quantity.Value).GetData());
            }
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Height));
            db.Write(WriteOptions.Default, batch);
            current_block_height = block.Height;
        }
コード例 #10
0
        private void Persist(Block block)
        {
            WriteBatch batch = new WriteBatch();
            DbCache <UInt160, AccountState>     accounts     = new DbCache <UInt160, AccountState>(db, DataEntryPrefix.ST_Account);
            DbCache <UInt256, UnspentCoinState> unspentcoins = new DbCache <UInt256, UnspentCoinState>(db, DataEntryPrefix.ST_Coin);
            DbCache <UInt256, SpentCoinState>   spentcoins   = new DbCache <UInt256, SpentCoinState>(db, DataEntryPrefix.ST_SpentCoin);
            DbCache <ECPoint, ValidatorState>   validators   = new DbCache <ECPoint, ValidatorState>(db, DataEntryPrefix.ST_Validator);
            DbCache <UInt256, AssetState>       assets       = new DbCache <UInt256, AssetState>(db, DataEntryPrefix.ST_Asset);
            DbCache <UInt160, ContractState>    contracts    = new DbCache <UInt160, ContractState>(db, DataEntryPrefix.ST_Contract);
            DbCache <StorageKey, StorageItem>   storages     = new DbCache <StorageKey, StorageItem>(db, DataEntryPrefix.ST_Storage);
            List <NotifyEventArgs> notifications             = new List <NotifyEventArgs>();
            long amount_sysfee = GetSysFeeAmount(block.PrevHash) + (long)block.Transactions.Sum(p => p.SystemFee);

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim()));
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Index).Add(tx.ToArray()));
                unspentcoins.Add(tx.Hash, new UnspentCoinState
                {
                    Items = Enumerable.Repeat(CoinState.Confirmed, tx.Outputs.Length).ToArray()
                });
                foreach (TransactionOutput output in tx.Outputs)
                {
                    AccountState account = accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash));
                    if (account.Balances.ContainsKey(output.AssetId))
                    {
                        account.Balances[output.AssetId] += output.Value;
                    }
                    else
                    {
                        account.Balances[output.AssetId] = output.Value;
                    }
                }
                foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash))
                {
                    int         height;
                    Transaction tx_prev = GetTransaction(ReadOptions.Default, group.Key, out height);
                    foreach (CoinReference input in group)
                    {
                        unspentcoins.GetAndChange(input.PrevHash).Items[input.PrevIndex] |= CoinState.Spent;
                        if (tx_prev.Outputs[input.PrevIndex].AssetId.Equals(GoverningToken.Hash))
                        {
                            spentcoins.GetAndChange(input.PrevHash, () => new SpentCoinState
                            {
                                TransactionHash   = input.PrevHash,
                                TransactionHeight = (uint)height,
                                Items             = new Dictionary <ushort, uint>()
                            }).Items.Add(input.PrevIndex, block.Index);
                        }
                        accounts.GetAndChange(tx_prev.Outputs[input.PrevIndex].ScriptHash).Balances[tx_prev.Outputs[input.PrevIndex].AssetId] -= tx_prev.Outputs[input.PrevIndex].Value;
                    }
                }
                switch (tx.Type)
                {
                case TransactionType.RegisterTransaction:
                {
#pragma warning disable CS0612
                    RegisterTransaction rtx = (RegisterTransaction)tx;
                    assets.Add(tx.Hash, new AssetState
                        {
                            AssetId    = rtx.Hash,
                            AssetType  = rtx.AssetType,
                            Name       = rtx.Name,
                            Amount     = rtx.Amount,
                            Available  = Fixed8.Zero,
                            Precision  = rtx.Precision,
                            Fee        = Fixed8.Zero,
                            FeeAddress = new UInt160(),
                            Owner      = rtx.Owner,
                            Admin      = rtx.Admin,
                            Issuer     = rtx.Admin,
                            Expiration = block.Index + 2 * 2000000,
                            IsFrozen   = false
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        assets.GetAndChange(result.AssetId).Available -= result.Amount;
                    }
                    break;

                case TransactionType.ClaimTransaction:
                    foreach (CoinReference input in ((ClaimTransaction)tx).Claims)
                    {
                        if (spentcoins.TryGet(input.PrevHash)?.Items.Remove(input.PrevIndex) == true)
                        {
                            spentcoins.GetAndChange(input.PrevHash);
                        }
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
#pragma warning disable CS0612
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    validators.GetOrAdd(enroll_tx.PublicKey, () => new ValidatorState
                        {
                            PublicKey = enroll_tx.PublicKey
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.PublishTransaction:
                {
#pragma warning disable CS0612
                    PublishTransaction publish_tx = (PublishTransaction)tx;
                    contracts.GetOrAdd(publish_tx.ScriptHash, () => new ContractState
                        {
                            Script             = publish_tx.Script,
                            ParameterList      = publish_tx.ParameterList,
                            ReturnType         = publish_tx.ReturnType,
                            ContractProperties = (ContractPropertyState)Convert.ToByte(publish_tx.NeedStorage),
                            Name        = publish_tx.Name,
                            CodeVersion = publish_tx.CodeVersion,
                            Author      = publish_tx.Author,
                            Email       = publish_tx.Email,
                            Description = publish_tx.Description
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.InvocationTransaction:
                {
                    InvocationTransaction itx          = (InvocationTransaction)tx;
                    CachedScriptTable     script_table = new CachedScriptTable(contracts);
                    StateMachine          service      = new StateMachine(accounts, validators, assets, contracts, storages);
                    ApplicationEngine     engine       = new ApplicationEngine(TriggerType.Application, itx, script_table, service, itx.Gas);
                    engine.LoadScript(itx.Script, false);
                    if (engine.Execute())
                    {
                        service.Commit();
                        notifications.AddRange(service.Notifications);
                    }
                }
                break;
                }
            }
            if (notifications.Count > 0)
            {
                OnNotify(block, notifications.ToArray());
            }
            accounts.DeleteWhere((k, v) => !v.IsFrozen && v.Votes.Length == 0 && v.Balances.All(p => p.Value <= Fixed8.Zero));
            accounts.Commit(batch);
            unspentcoins.DeleteWhere((k, v) => v.Items.All(p => p.HasFlag(CoinState.Spent)));
            unspentcoins.Commit(batch);
            spentcoins.DeleteWhere((k, v) => v.Items.Count == 0);
            spentcoins.Commit(batch);
            validators.Commit(batch);
            assets.Commit(batch);
            contracts.Commit(batch);
            storages.Commit(batch);
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Index));
            db.Write(WriteOptions.Default, batch);
            current_block_height = block.Index;
        }
コード例 #11
0
        public void Verify_Success()
        {
            var testee = AutoMockContainer.Create <TransactionOperationManager>();

            var transaction = new EnrollmentTransaction
            {
                Attributes = new []
                {
                    new TransactionAttribute
                    {
                        Usage = TransactionAttributeUsage.ContractHash
                    }
                },
                Inputs = new[]
                {
                    new CoinReference
                    {
                        PrevHash  = UInt256.Zero,
                        PrevIndex = 1
                    },
                    new CoinReference
                    {
                        PrevHash  = UInt256.Zero,
                        PrevIndex = 2
                    }
                },
                Outputs = new[]
                {
                    new TransactionOutput
                    {
                        AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
                        Value   = new Fixed8(200000000)
                    }
                },
                Witness = new []
                {
                    new Witness()
                }
            };

            var transactionOfPreviousHash = new Transaction
            {
                Outputs = new []
                {
                    new TransactionOutput(), // it's not using the first because PrevIndex is 1
                    new TransactionOutput
                    {
                        AssetId = UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"),
                        Value   = new Fixed8(200000000)
                    },
                    new TransactionOutput
                    {
                        AssetId = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7"),
                        Value   = new Fixed8(200000000)
                    }
                }
            };

            var transactionModelMock = this.AutoMockContainer.GetMock <ITransactionRepository>();

            transactionModelMock
            .Setup(b => b.IsDoubleSpend(transaction))
            .Returns(false);
            transactionModelMock
            .Setup(x => x.GetTransaction(It.IsAny <UInt256>()))
            .ReturnsAsync(() => transactionOfPreviousHash);

            this.AutoMockContainer
            .GetMock <IAssetRepository>()
            .Setup(b => b.GetAsset(It.IsAny <UInt256>()))
            .ReturnsAsync(() => new Asset
            {
                AssetType = AssetType.GoverningToken
            });

            var transactionContextMock = this.AutoMockContainer.GetMock <ITransactionContext>();

            transactionContextMock
            .SetupGet(x => x.UtilityTokenHash)
            .Returns(UInt256.Parse("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"));
            transactionContextMock
            .Setup(x => x.GetSystemFee(It.IsAny <Transaction>()))
            .Returns(new Fixed8(190000000));

            this.AutoMockContainer
            .GetMock <IWitnessOperationsManager>()
            .Setup(x => x.Verify(It.IsAny <Witness>()))
            .Returns(true);

            var result = testee.Verify(transaction);

            result.Should().BeTrue();
        }
コード例 #12
0
        private void Persist(Block block)
        {
            MultiValueDictionary <UInt256, ushort> unspents = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value = new byte[0];
                db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(p), out value);
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            MultiValueDictionary <UInt256, ushort> unspent_antshares = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value = new byte[0];
                db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(p), out value);
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            MultiValueDictionary <UInt256, ushort> unspent_votes = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value = new byte[0];
                db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(p), out value);
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            Dictionary <UInt256, Fixed8> quantities = new Dictionary <UInt256, Fixed8>();
            WriteBatch batch = new WriteBatch();

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), block.Trim());
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), tx.ToArray());
                switch (tx.Type)
                {
                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        if (quantities.ContainsKey(result.AssetId))
                        {
                            quantities[result.AssetId] -= result.Amount;
                        }
                        else
                        {
                            quantities.Add(result.AssetId, -result.Amount);
                        }
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(tx.Hash), true);
                }
                break;

                case TransactionType.VotingTransaction:
                    unspent_votes.AddEmpty(tx.Hash);
                    for (ushort index = 0; index < tx.Outputs.Length; index++)
                    {
                        if (tx.Outputs[index].AssetId == AntShare.Hash)
                        {
                            unspent_votes.Add(tx.Hash, index);
                        }
                    }
                    break;

                case TransactionType.RegisterTransaction:
                {
                    RegisterTransaction reg_tx = (RegisterTransaction)tx;
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Asset).Add(reg_tx.Hash), true);
                }
                break;
                }
                unspents.AddEmpty(tx.Hash);
                unspent_antshares.AddEmpty(tx.Hash);
                for (ushort index = 0; index < tx.Outputs.Length; index++)
                {
                    unspents.Add(tx.Hash, index);
                    if (tx.Outputs[index].AssetId == AntShare.Hash)
                    {
                        unspent_antshares.Add(tx.Hash, index);
                    }
                }
            }
            foreach (TransactionInput input in block.Transactions.SelectMany(p => p.GetAllInputs()))
            {
                if (input.PrevIndex == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(input.PrevHash));
                }
                unspents.Remove(input.PrevHash, input.PrevIndex);
                unspent_antshares.Remove(input.PrevHash, input.PrevIndex);
                unspent_votes.Remove(input.PrevHash, input.PrevIndex);
            }
            //统计AntCoin的发行量
            {
                Fixed8 amount_in  = block.Transactions.SelectMany(p => p.References.Values.Where(o => o.AssetId == AntCoin.Hash)).Sum(p => p.Value);
                Fixed8 amount_out = block.Transactions.SelectMany(p => p.Outputs.Where(o => o.AssetId == AntCoin.Hash)).Sum(p => p.Value);
                if (amount_in != amount_out)
                {
                    quantities.Add(AntCoin.Hash, amount_out - amount_in);
                }
            }
            foreach (var unspent in unspents)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var unspent in unspent_antshares)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_AntShare).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var unspent in unspent_votes)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var quantity in quantities)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_QuantityIssued).Add(quantity.Key), (GetQuantityIssued(quantity.Key) + quantity.Value).GetData());
            }
            current_block_hash   = block.Hash;
            current_block_height = block.Hash == GenesisBlock.Hash ? 0 : current_block_height + 1;
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(current_block_height));
            db.Write(WriteOptions.Default, batch);
        }
コード例 #13
0
        private void Persist(Block block)
        {
            const int UnclaimedItemSize = sizeof(ushort) + sizeof(uint);
            MultiValueDictionary <UInt256, ushort> unspents = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(p), out value))
                {
                    value = new byte[0];
                }
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            MultiValueDictionary <UInt256, ushort, uint> unclaimed = new MultiValueDictionary <UInt256, ushort, uint>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(p), out value))
                {
                    value = new byte[0];
                }
                byte[] data = value.ToArray();
                return(Enumerable.Range(0, data.Length / UnclaimedItemSize).ToDictionary(i => BitConverter.ToUInt16(data, i * UnclaimedItemSize), i => BitConverter.ToUInt32(data, i * UnclaimedItemSize + sizeof(ushort))));
            });
            MultiValueDictionary <UInt256, ushort> unspent_votes = new MultiValueDictionary <UInt256, ushort>(p =>
            {
                Slice value;
                if (!db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(p), out value))
                {
                    value = new byte[0];
                }
                return(new HashSet <ushort>(value.ToArray().GetUInt16Array()));
            });
            Dictionary <UInt256, Fixed8> quantities = new Dictionary <UInt256, Fixed8>();
            WriteBatch batch         = new WriteBatch();
            long       amount_sysfee = GetSysFeeAmount(block.PrevBlock) + (long)block.Transactions.Sum(p => p.SystemFee);

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Header).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim()));
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Height).Add(tx.ToArray()));
                if (tx.Attributes.Any(p => p.Usage == TransactionAttributeUsage.Vote))
                {
                    unspent_votes.AddEmpty(tx.Hash);
                    for (ushort index = 0; index < tx.Outputs.Length; index++)
                    {
                        if (tx.Outputs[index].AssetId == AntShare.Hash)
                        {
                            unspent_votes.Add(tx.Hash, index);
                        }
                    }
                }
                switch (tx.Type)
                {
                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        if (quantities.ContainsKey(result.AssetId))
                        {
                            quantities[result.AssetId] -= result.Amount;
                        }
                        else
                        {
                            quantities.Add(result.AssetId, -result.Amount);
                        }
                    }
                    break;

                case TransactionType.ClaimTransaction:
                    foreach (TransactionInput input in ((ClaimTransaction)tx).Claims)
                    {
                        unclaimed.Remove(input.PrevHash, input.PrevIndex);
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(tx.Hash), true);
                }
                break;

                case TransactionType.PublishTransaction:
                    foreach (byte[] script in ((PublishTransaction)tx).Contracts)
                    {
                        batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Contract).Add(script.ToScriptHash()), script);
                    }
                    break;
                }
                unspents.AddEmpty(tx.Hash);
                for (ushort index = 0; index < tx.Outputs.Length; index++)
                {
                    unspents.Add(tx.Hash, index);
                }
            }
            foreach (var group in block.Transactions.SelectMany(p => p.GetAllInputs()).GroupBy(p => p.PrevHash))
            {
                int         height;
                Transaction tx = GetTransaction(ReadOptions.Default, group.Key, out height);
                foreach (TransactionInput input in group)
                {
                    if (input.PrevIndex == 0)
                    {
                        batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Enrollment).Add(input.PrevHash));
                    }
                    unspents.Remove(input.PrevHash, input.PrevIndex);
                    unspent_votes.Remove(input.PrevHash, input.PrevIndex);
                    if (tx?.Outputs[input.PrevIndex].AssetId == AntShare.Hash)
                    {
                        unclaimed.Add(input.PrevHash, input.PrevIndex, block.Height);
                    }
                }
            }
            foreach (var unspent in unspents)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unspent).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var spent in unclaimed)
            {
                if (spent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(spent.Key));
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream(spent.Value.Count * UnclaimedItemSize))
                        using (BinaryWriter w = new BinaryWriter(ms))
                        {
                            foreach (var pair in spent.Value)
                            {
                                w.Write(pair.Key);
                                w.Write(pair.Value);
                            }
                            w.Flush();
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Unclaimed).Add(spent.Key), ms.ToArray());
                        }
                }
            }
            foreach (var unspent in unspent_votes)
            {
                if (unspent.Value.Count == 0)
                {
                    batch.Delete(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key));
                }
                else
                {
                    batch.Put(SliceBuilder.Begin(DataEntryPrefix.IX_Vote).Add(unspent.Key), unspent.Value.ToByteArray());
                }
            }
            foreach (var quantity in quantities)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_QuantityIssued).Add(quantity.Key), (GetQuantityIssued(quantity.Key) + quantity.Value).GetData());
            }
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Height));
            // There's a bug in .Net Core.
            // When calling DB.Write(), it will throw LevelDBException sometimes.
            // But when you try to catch the exception, the bug disappears.
            // We shall remove the "try...catch" clause when Microsoft fix the bug.
            byte retry = 0;

            while (true)
            {
                try
                {
                    db.Write(WriteOptions.Default, batch);
                    break;
                }
                catch (LevelDBException ex)
                {
                    if (++retry >= 4)
                    {
                        throw;
                    }
                    File.AppendAllText("leveldb.log", ex.Message + "\r\n");
                }
            }
            current_block_height = block.Height;
        }
コード例 #14
0
        private void Persist(Block block)
        {
            bool change_cm_merkle_tree = false;

            WriteBatch batch = new WriteBatch();
            DbCache <UInt160, AccountState>     accounts     = new DbCache <UInt160, AccountState>(db, DataEntryPrefix.ST_Account);
            DbCache <UInt256, UnspentCoinState> unspentcoins = new DbCache <UInt256, UnspentCoinState>(db, DataEntryPrefix.ST_Coin);
            DbCache <UInt256, SpentCoinState>   spentcoins   = new DbCache <UInt256, SpentCoinState>(db, DataEntryPrefix.ST_SpentCoin);
            DbCache <ECPoint, ValidatorState>   validators   = new DbCache <ECPoint, ValidatorState>(db, DataEntryPrefix.ST_Validator);
            DbCache <UInt256, AssetState>       assets       = new DbCache <UInt256, AssetState>(db, DataEntryPrefix.ST_Asset);
            DbCache <UInt160, ContractState>    contracts    = new DbCache <UInt160, ContractState>(db, DataEntryPrefix.ST_Contract);
            DbCache <StorageKey, StorageItem>   storages     = new DbCache <StorageKey, StorageItem>(db, DataEntryPrefix.ST_Storage);
            List <NotifyEventArgs> notifications             = new List <NotifyEventArgs>();
            long amount_sysfee = GetSysFeeAmount(block.PrevHash) + (long)block.Transactions.Sum(p => p.SystemFee);

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim()));
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Index).Add(tx.ToArray()));
                unspentcoins.Add(tx.Hash, new UnspentCoinState
                {
                    Items = Enumerable.Repeat(CoinState.Confirmed, tx.Outputs.Length).ToArray()
                });
                foreach (TransactionOutput output in tx.Outputs)
                {
                    AccountState account = accounts.GetAndChange(output.ScriptHash, () => new AccountState(output.ScriptHash));
                    if (account.Balances.ContainsKey(output.AssetId))
                    {
                        account.Balances[output.AssetId] += output.Value;
                    }
                    else
                    {
                        account.Balances[output.AssetId] = output.Value;
                    }
                }
                foreach (var group in tx.Inputs.GroupBy(p => p.PrevHash))
                {
                    int         height;
                    Transaction tx_prev = GetTransaction(ReadOptions.Default, group.Key, out height);
                    foreach (CoinReference input in group)
                    {
                        unspentcoins.GetAndChange(input.PrevHash).Items[input.PrevIndex] |= CoinState.Spent;
                        if (tx_prev.Outputs[input.PrevIndex].AssetId.Equals(GoverningToken.Hash))
                        {
                            spentcoins.GetAndChange(input.PrevHash, () => new SpentCoinState
                            {
                                TransactionHash   = input.PrevHash,
                                TransactionHeight = (uint)height,
                                Items             = new Dictionary <ushort, uint>()
                            }).Items.Add(input.PrevIndex, block.Index);
                        }
                        accounts.GetAndChange(tx_prev.Outputs[input.PrevIndex].ScriptHash).Balances[tx_prev.Outputs[input.PrevIndex].AssetId] -= tx_prev.Outputs[input.PrevIndex].Value;
                    }
                }
                switch (tx.Type)
                {
                case TransactionType.RingConfidentialTransaction:
                {
                    if (tx is RingConfidentialTransaction ctx)
                    {
                        for (int i = 0; i < ctx.RingCTSig.Count; i++)
                        {
                            // Add the I Commitment to blockchain.
                            for (int j = 0; j < ctx.RingCTSig[i].MG.II.Count; j++)
                            {
                                batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_RingCTCommitment).Add(ctx.RingCTSig[i].MG.II[j]), SliceBuilder.Begin().Add(ctx.RingCTSig[i].AssetID));
                            }
                        }
                    }
                }
                break;

                case TransactionType.AnonymousContractTransaction:
                {
                    if (tx is AnonymousContractTransaction ctx)
                    {
                        for (int jsIndex = 0; jsIndex < ctx.byJoinSplit.Count; jsIndex++)
                        {
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_Nullifier).Add(ctx.Nullifiers(jsIndex)[0]), SliceBuilder.Begin().Add(ctx.Asset_ID(jsIndex)));
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_Nullifier).Add(ctx.Nullifiers(jsIndex)[1]), SliceBuilder.Begin().Add(ctx.Asset_ID(jsIndex)));

                            SnarkDllApi.AppendCommitment(gCmMerkleTree, ctx.Commitments(jsIndex)[0].ToArray());
                            SnarkDllApi.AppendCommitment(gCmMerkleTree, ctx.Commitments(jsIndex)[1].ToArray());
                        }

                        change_cm_merkle_tree = true;
                    }
                }
                break;

                case TransactionType.RegisterTransaction:
                {
#pragma warning disable CS0612
                    RegisterTransaction rtx = (RegisterTransaction)tx;
                    assets.Add(tx.Hash, new AssetState
                        {
                            AssetId    = rtx.Hash,
                            AssetType  = rtx.AssetType,
                            Name       = rtx.Name,
                            Amount     = rtx.Amount,
                            Available  = Fixed8.Zero,
                            Precision  = rtx.Precision,
                            Fee        = rtx.T_Fee,
                            FeeMin     = rtx.T_Fee_Min,
                            FeeMax     = rtx.T_Fee_Max,
                            AFee       = rtx.A_Fee,
                            FeeAddress = new UInt160(),
                            Owner      = rtx.Owner,
                            Admin      = rtx.Admin,
                            Issuer     = rtx.Admin,
                            Expiration = block.Index + 2 * 2000000,
                            IsFrozen   = false
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        assets.GetAndChange(result.AssetId).Available -= result.Amount;
                    }
                    break;

                case TransactionType.ClaimTransaction:
                    foreach (CoinReference input in ((ClaimTransaction)tx).Claims)
                    {
                        if (spentcoins.TryGet(input.PrevHash)?.Items.Remove(input.PrevIndex) == true)
                        {
                            spentcoins.GetAndChange(input.PrevHash);
                        }
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
#pragma warning disable CS0612
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    validators.GetOrAdd(enroll_tx.PublicKey, () => new ValidatorState
                        {
                            PublicKey = enroll_tx.PublicKey
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.PublishTransaction:
                {
#pragma warning disable CS0612
                    PublishTransaction publish_tx = (PublishTransaction)tx;
                    contracts.GetOrAdd(publish_tx.ScriptHash, () => new ContractState
                        {
                            Script        = publish_tx.Script,
                            ParameterList = publish_tx.ParameterList,
                            ReturnType    = publish_tx.ReturnType,
                            HasStorage    = publish_tx.NeedStorage,
                            Name          = publish_tx.Name,
                            CodeVersion   = publish_tx.CodeVersion,
                            Author        = publish_tx.Author,
                            Email         = publish_tx.Email,
                            Description   = publish_tx.Description
                        });
#pragma warning restore CS0612
                }
                break;

                case TransactionType.InvocationTransaction:
                {
                    InvocationTransaction itx          = (InvocationTransaction)tx;
                    CachedScriptTable     script_table = new CachedScriptTable(contracts);
                    StateMachine          service      = new StateMachine(accounts, validators, assets, contracts, storages);
                    ApplicationEngine     engine       = new ApplicationEngine(TriggerType.Application, itx, script_table, service, itx.Gas);
                    engine.LoadScript(itx.Script, false);
                    if (engine.Execute())
                    {
                        service.Commit();
                        notifications.AddRange(service.Notifications);
                    }
                }
                break;
                }
            }

            if (change_cm_merkle_tree == true)
            {
                int[] outLen = new int[1];
                outLen[0] = 0;
                IntPtr ptrTree = SnarkDllApi.GetCMTreeInBinary(gCmMerkleTree, outLen);

                byte[] byTree = new byte[outLen[0]];
                System.Runtime.InteropServices.Marshal.Copy(ptrTree, byTree, 0, outLen[0]);

                IntPtr ptrRt1 = SnarkDllApi.GetCMRoot(gCmMerkleTree);

                byte[] by_rt = new byte[32];
                System.Runtime.InteropServices.Marshal.Copy(ptrRt1, by_rt, 0, 32);

                UInt256 current_rt = new UInt256(by_rt);

                db.Put(WriteOptions.Default, SliceBuilder.Begin(DataEntryPrefix.AM_CmMerkleTree), byTree);

                mCmMerkleRoots.Add(current_rt);

                while ((int)mCmMerkleRoots.Count - 5 >= stored_cm_root_count)
                {
                    using (MemoryStream ms = new MemoryStream())
                        using (BinaryWriter w = new BinaryWriter(ms))
                        {
                            w.Write(mCmMerkleRoots.Skip((int)stored_cm_root_count).Take(5).ToArray());
                            w.Flush();
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_MerkleRoot).Add(stored_cm_root_count), ms.ToArray());
                        }
                    stored_cm_root_count += 5;
                }

                if (mCmMerkleRoots.Count > stored_cm_root_count)
                {
                    using (MemoryStream ms = new MemoryStream())
                        using (BinaryWriter w = new BinaryWriter(ms))
                        {
                            w.Write(mCmMerkleRoots.Skip((int)stored_cm_root_count).ToArray());
                            w.Flush();
                            batch.Put(SliceBuilder.Begin(DataEntryPrefix.ST_MerkleRoot).Add(stored_cm_root_count), ms.ToArray());
                        }
                }
            }

            if (notifications.Count > 0)
            {
                OnNotify(block, notifications.ToArray());
            }
            accounts.DeleteWhere((k, v) => !v.IsFrozen && v.Votes.Length == 0 && v.Balances.All(p => p.Value <= Fixed8.Zero));
            accounts.Commit(batch);
            unspentcoins.DeleteWhere((k, v) => v.Items.All(p => p.HasFlag(CoinState.Spent)));
            unspentcoins.Commit(batch);
            spentcoins.DeleteWhere((k, v) => v.Items.Count == 0);
            spentcoins.Commit(batch);
            validators.Commit(batch);
            assets.Commit(batch);
            contracts.Commit(batch);
            storages.Commit(batch);
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Index));
            db.Write(WriteOptions.Default, batch);
            current_block_height = block.Index;
        }
コード例 #15
0
        private void Persist(Block block)
        {
            DataCache <UInt160, AccountState>     accounts     = new DataCache <UInt160, AccountState>(db, DataEntryPrefix.ST_Account);
            DataCache <UInt256, UnspentCoinState> unspentcoins = new DataCache <UInt256, UnspentCoinState>(db, DataEntryPrefix.ST_Coin);
            DataCache <UInt256, SpentCoinState>   spentcoins   = new DataCache <UInt256, SpentCoinState>(db, DataEntryPrefix.ST_SpentCoin);
            DataCache <ECPoint, ValidatorState>   validators   = new DataCache <ECPoint, ValidatorState>(db, DataEntryPrefix.ST_Validator);
            DataCache <UInt256, AssetState>       assets       = new DataCache <UInt256, AssetState>(db, DataEntryPrefix.ST_Asset);
            DataCache <UInt160, ContractState>    contracts    = new DataCache <UInt160, ContractState>(db, DataEntryPrefix.ST_Contract);
            WriteBatch batch         = new WriteBatch();
            long       amount_sysfee = GetSysFeeAmount(block.PrevHash) + (long)block.Transactions.Sum(p => p.SystemFee);

            batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(block.Hash), SliceBuilder.Begin().Add(amount_sysfee).Add(block.Trim()));
            foreach (Transaction tx in block.Transactions)
            {
                batch.Put(SliceBuilder.Begin(DataEntryPrefix.DATA_Transaction).Add(tx.Hash), SliceBuilder.Begin().Add(block.Index).Add(tx.ToArray()));
                switch (tx.Type)
                {
                case TransactionType.RegisterTransaction:
                {
                    RegisterTransaction rtx = (RegisterTransaction)tx;
                    assets.Add(tx.Hash, new AssetState
                        {
                            AssetId    = rtx.Hash,
                            AssetType  = rtx.AssetType,
                            Name       = rtx.Name,
                            Amount     = rtx.Amount,
                            Available  = Fixed8.Zero,
                            Precision  = rtx.Precision,
                            Fee        = Fixed8.Zero,
                            FeeAddress = new UInt160(),
                            Owner      = rtx.Owner,
                            Admin      = rtx.Admin,
                            Issuer     = rtx.Admin,
                            Expiration = block.Index + 2000000,
                            IsFrozen   = false
                        });
                }
                break;

                case TransactionType.IssueTransaction:
                    foreach (TransactionResult result in tx.GetTransactionResults().Where(p => p.Amount < Fixed8.Zero))
                    {
                        assets[result.AssetId].Available -= result.Amount;
                    }
                    break;

                case TransactionType.ClaimTransaction:
                    foreach (CoinReference input in ((ClaimTransaction)tx).Claims)
                    {
                        spentcoins.TryGet(input.PrevHash)?.Items.Remove(input.PrevIndex);
                    }
                    break;

                case TransactionType.EnrollmentTransaction:
                {
                    EnrollmentTransaction enroll_tx = (EnrollmentTransaction)tx;
                    validators.Add(enroll_tx.PublicKey, new ValidatorState
                        {
                            PublicKey = enroll_tx.PublicKey
                        });
                }
                break;

                case TransactionType.PublishTransaction:
                {
                    PublishTransaction publish_tx = (PublishTransaction)tx;
                    contracts.GetOrAdd(publish_tx.Code.ScriptHash, () => new ContractState
                        {
                            Script     = publish_tx.Code.Script,
                            HasStorage = false
                        });
                }
                break;
                }
                unspentcoins.Add(tx.Hash, new UnspentCoinState
                {
                    Items = Enumerable.Repeat(CoinState.Confirmed, tx.Outputs.Length).ToArray()
                });
                foreach (TransactionOutput output in tx.Outputs)
                {
                    AccountState account = accounts.GetOrAdd(output.ScriptHash, () => new AccountState
                    {
                        ScriptHash = output.ScriptHash,
                        IsFrozen   = false,
                        Votes      = new ECPoint[0],
                        Balances   = new Dictionary <UInt256, Fixed8>()
                    });
                    if (account.Balances.ContainsKey(output.AssetId))
                    {
                        account.Balances[output.AssetId] += output.Value;
                    }
                    else
                    {
                        account.Balances[output.AssetId] = output.Value;
                    }
                }
            }
            foreach (var group in block.Transactions.SelectMany(p => p.Inputs).GroupBy(p => p.PrevHash))
            {
                int         height;
                Transaction tx = GetTransaction(ReadOptions.Default, group.Key, out height);
                foreach (CoinReference input in group)
                {
                    unspentcoins[input.PrevHash].Items[input.PrevIndex] |= CoinState.Spent;
                    if (tx.Outputs[input.PrevIndex].AssetId.Equals(SystemShare.Hash))
                    {
                        spentcoins.GetOrAdd(input.PrevHash, () => new SpentCoinState
                        {
                            TransactionHash   = input.PrevHash,
                            TransactionHeight = (uint)height,
                            Items             = new Dictionary <ushort, uint>()
                        }).Items.Add(input.PrevIndex, block.Index);
                    }
                    accounts[tx.Outputs[input.PrevIndex].ScriptHash].Balances[tx.Outputs[input.PrevIndex].AssetId] -= tx.Outputs[input.PrevIndex].Value;
                }
            }
            accounts.DeleteWhere((k, v) => !v.IsFrozen && v.Votes.Length == 0 && v.Balances.All(p => p.Value <= Fixed8.Zero));
            accounts.Commit(batch);
            unspentcoins.DeleteWhere((k, v) => v.Items.All(p => p.HasFlag(CoinState.Spent)));
            unspentcoins.Commit(batch);
            spentcoins.DeleteWhere((k, v) => v.Items.Count == 0);
            spentcoins.Commit(batch);
            validators.Commit(batch);
            assets.Commit(batch);
            contracts.Commit(batch);
            batch.Put(SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock), SliceBuilder.Begin().Add(block.Hash).Add(block.Index));
            db.Write(WriteOptions.Default, batch);
            current_block_height = block.Index;
        }