Пример #1
0
        private void RecordTransferHistory(StoreView snapshot, UInt160 scriptHash, UInt160 from, UInt160 to, BigInteger amount, UInt256 txHash, ref ushort transferIndex)
        {
            if (!_shouldTrackHistory)
            {
                return;
            }

            Header header = snapshot.GetHeader(snapshot.CurrentBlockHash);

            if (_recordNullAddressHistory || from != UInt160.Zero)
            {
                _transfersSent.Add(new Nep5TransferKey(from, header.Timestamp, scriptHash, transferIndex),
                                   new Nep5Transfer
                {
                    Amount         = amount,
                    UserScriptHash = to,
                    BlockIndex     = snapshot.Height,
                    TxHash         = txHash
                });
            }

            if (_recordNullAddressHistory || to != UInt160.Zero)
            {
                _transfersReceived.Add(new Nep5TransferKey(to, header.Timestamp, scriptHash, transferIndex),
                                       new Nep5Transfer
                {
                    Amount         = amount,
                    UserScriptHash = from,
                    BlockIndex     = snapshot.Height,
                    TxHash         = txHash
                });
            }
            transferIndex++;
        }
Пример #2
0
        internal static (BigInteger Value, bool State) Check_UnclaimedGas(StoreView snapshot, byte[] address)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot);

            engine.LoadScript(NativeContract.NEO.Script);

            var script = new ScriptBuilder();

            script.EmitPush(snapshot.PersistingBlock.Index);
            script.EmitPush(address);
            script.EmitPush(2);
            script.Emit(OpCode.PACK);
            script.EmitPush("unclaimedGas");
            engine.LoadScript(script.ToArray());

            if (engine.Execute() == VMState.FAULT)
            {
                return(BigInteger.Zero, false);
            }

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Integer));

            return(result.GetInteger(), true);
        }
Пример #3
0
 protected ApplicationEngine(TriggerType trigger, IVerifiable container, StoreView snapshot, long gas)
 {
     this.Trigger         = trigger;
     this.ScriptContainer = container;
     this.Snapshot        = snapshot;
     this.gas_amount      = gas;
 }
Пример #4
0
        internal static (bool State, bool Result) Check_UnregisterCandidate(StoreView snapshot, byte[] pubkey)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application,
                                                  new Nep5NativeContractExtensions.ManualWitness(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1)).ToScriptHash()), snapshot);

            engine.LoadScript(NativeContract.NEO.Script);

            var script = new ScriptBuilder();

            script.EmitPush(pubkey);
            script.EmitPush(1);
            script.Emit(OpCode.PACK);
            script.EmitPush("unregisterCandidate");
            engine.LoadScript(script.ToArray());

            if (engine.Execute() == VMState.FAULT)
            {
                return(false, false);
            }

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Boolean));

            return(true, result.GetBoolean());
        }
Пример #5
0
        internal static (VM.Types.Boolean Value, bool State) Check_SetGasPerBlock(StoreView snapshot, BigInteger gasPerBlock)
        {
            UInt160 committeeMultiSigAddr = NativeContract.NEO.GetCommitteeAddress(snapshot);
            var     engine = ApplicationEngine.Create(TriggerType.Application, new Nep5NativeContractExtensions.ManualWitness(committeeMultiSigAddr), snapshot);

            engine.LoadScript(NativeContract.NEO.Script);

            var script = new ScriptBuilder();

            script.EmitPush(gasPerBlock);
            script.EmitPush(1);
            script.Emit(OpCode.PACK);
            script.EmitPush("setGasPerBlock");
            engine.LoadScript(script.ToArray());

            if (engine.Execute() == VMState.FAULT)
            {
                return(false, false);
            }

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Boolean));

            return(((VM.Types.Boolean)result).GetBoolean(), true);
        }
Пример #6
0
        internal static (bool State, bool Result) Check_Vote(StoreView snapshot, byte[] account, byte[] pubkey, bool signAccount)
        {
            var engine = ApplicationEngine.Create(TriggerType.Application,
                                                  new Nep5NativeContractExtensions.ManualWitness(signAccount ? new UInt160(account) : UInt160.Zero), snapshot);

            engine.LoadScript(NativeContract.NEO.Script);

            var script = new ScriptBuilder();

            if (pubkey is null)
            {
                script.Emit(OpCode.PUSHNULL);
            }
            else
            {
                script.EmitPush(pubkey);
            }
            script.EmitPush(account);
            script.EmitPush(2);
            script.Emit(OpCode.PACK);
            script.EmitPush("vote");
            engine.LoadScript(script.ToArray());

            if (engine.Execute() == VMState.FAULT)
            {
                return(false, false);
            }

            var result = engine.ResultStack.Pop();

            result.Should().BeOfType(typeof(VM.Types.Boolean));

            return(true, result.GetBoolean());
        }
Пример #7
0
        private BigInteger CalculateBonus(StoreView snapshot, BigInteger value, uint start, uint end)
        {
            if (value.IsZero || start >= end)
            {
                return(BigInteger.Zero);
            }
            if (value.Sign < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(value));
            }

            GasRecord  gasRecord = snapshot.Storages[CreateStorageKey(Prefix_GasPerBlock)].GetInteroperable <GasRecord>();
            BigInteger sum       = 0;

            for (var i = gasRecord.Count - 1; i >= 0; i--)
            {
                var currentIndex = gasRecord[i].Index;
                if (currentIndex >= end)
                {
                    continue;
                }
                if (currentIndex > start)
                {
                    sum += gasRecord[i].GasPerBlock * (end - currentIndex);
                    end  = currentIndex;
                }
                else
                {
                    sum += gasRecord[i].GasPerBlock * (end - start);
                    break;
                }
            }
            return(value * sum * NeoHolderRewardRatio / 100 / TotalAmount);
        }
Пример #8
0
 public UInt160[] GetScriptHashesForVerifying(StoreView snapshot)
 {
     return(new UInt160[]
     {
         UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
     });
 }
Пример #9
0
    public static StoreView Load()
    {
        StoreView view = UIView.Load("Views/StoreView", OverriddenViewController.Instance.transform) as StoreView;

        view.name = "StoreView";
        return(view);
    }
Пример #10
0
        // Note: this must only be called from a single thread (the Blockchain actor)
        internal void UpdatePoolForBlockPersisted(Block block, StoreView snapshot)
        {
            LoadPolicy(snapshot);

            _txRwLock.EnterWriteLock();
            try
            {
                // First remove the transactions verified in the block.
                foreach (Transaction tx in block.Transactions)
                {
                    if (TryRemoveVerified(tx.Hash, out _))
                    {
                        continue;
                    }
                    TryRemoveUnVerified(tx.Hash, out _);
                }

                // Add all the previously verified transactions back to the unverified transactions
                InvalidateVerifiedTransactions();
            }
            finally
            {
                _txRwLock.ExitWriteLock();
            }

            // If we know about headers of future blocks, no point in verifying transactions from the unverified tx pool
            // until we get caught up.
            if (block.Index > 0 && block.Index < Blockchain.Singleton.HeaderHeight)
            {
                return;
            }

            ReverifyTransactions(_sortedTransactions, _unverifiedSortedTransactions,
                                 _maxTxPerBlock, MaxMillisecondsToReverifyTx, snapshot);
        }
Пример #11
0
 private void resetSnapshots()
 {
     this.store?.Dispose();
     this.store          = null;
     this.store          = this.path != null ? new RocksDBStore(this.path).GetStore() : new MemoryStore();
     this.snapshot       = new SnapshotView(this.store);
     this.clonedSnapshot = this.snapshot.Clone();
 }
Пример #12
0
 public ECPoint[] GetDesignatedByRole(StoreView snapshot, Role role)
 {
     if (!Enum.IsDefined(typeof(Role), role))
     {
         throw new ArgumentOutOfRangeException(nameof(role));
     }
     return(snapshot.Storages[CreateStorageKey((byte)role)].GetInteroperable <NodeList>().ToArray());
 }
Пример #13
0
 public BigInteger BalanceOf(StoreView snapshot, UInt160 owner)
 {
     if (owner is null)
     {
         throw new ArgumentNullException(nameof(owner));
     }
     return(snapshot.Storages.TryGet(CreateStorageKey(Prefix_Account).Add(owner))?.GetInteroperable <NFTAccountState>().Balance ?? BigInteger.Zero);
 }
Пример #14
0
 /// <summary>
 /// read nep5 from cache first
 /// </summary>
 /// <param name="assetId"></param>
 /// <param name="snapshot"></param>
 /// <returns></returns>
 public static AssetInfo GetAssetInfo(UInt160 assetId, StoreView snapshot)
 {
     if (_assets.ContainsKey(assetId))
     {
         return(_assets[assetId]);
     }
     return(GetAssetInfoFromChain(assetId, snapshot));
 }
Пример #15
0
        private int GetNextAvailableId(StoreView snapshot)
        {
            StorageItem item  = snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_NextAvailableId), () => new StorageItem(1));
            int         value = (int)(BigInteger)item;

            item.Add(1);
            return(value);
        }
Пример #16
0
 public ApplicationEngine(TriggerType trigger, IVerifiable container, StoreView snapshot, long gas, bool testMode = false)
 {
     this.gas_amount      = GasFree + gas;
     this.testMode        = testMode;
     this.Trigger         = trigger;
     this.ScriptContainer = container;
     this.Snapshot        = snapshot;
 }
Пример #17
0
        private void RegisterCandidateInternal(StoreView snapshot, ECPoint pubkey)
        {
            StorageKey     key   = CreateStorageKey(Prefix_Candidate).Add(pubkey);
            StorageItem    item  = snapshot.Storages.GetAndChange(key, () => new StorageItem(new CandidateState()));
            CandidateState state = item.GetInteroperable <CandidateState>();

            state.Registered = true;
        }
Пример #18
0
 public bool Verify(StoreView snapshot)
 {
     if (BlockIndex <= snapshot.Height)
     {
         return(false);
     }
     return(this.VerifyWitnesses(snapshot, 0_02000000));
 }
Пример #19
0
 private static bool IsTraceableBlock(StoreView snapshot, uint index)
 {
     if (index > snapshot.Height)
     {
         return(false);
     }
     return(index + ProtocolSettings.Default.MaxTraceableBlocks > snapshot.Height);
 }
Пример #20
0
 internal bool CheckPolicy(Transaction tx, StoreView snapshot)
 {
     UInt160[] blockedAccounts = GetBlockedAccounts(snapshot);
     if (blockedAccounts.Intersect(tx.GetScriptHashesForVerifying(snapshot)).Any())
     {
         return(false);
     }
     return(true);
 }
Пример #21
0
        public void TestSetup()
        {
            TestBlockchain.InitializeMockNeoSystem();
            _snapshot = Blockchain.Singleton.GetSnapshot();

            ApplicationEngine engine = ApplicationEngine.Create(TriggerType.OnPersist, null, _snapshot, new Block(), 0);

            NativeContract.ContractManagement.OnPersist(engine);
        }
Пример #22
0
 public void TestSetup()
 {
     TestBlockchain.InitializeMockNeoSystem();
     _snapshot = Blockchain.Singleton.GetSnapshot();
     _snapshot.PersistingBlock = new Block()
     {
         Index = 0
     };
 }
Пример #23
0
 public IEnumerable <(ECPoint PublicKey, BigInteger Votes)> GetCandidates(StoreView snapshot)
 {
     byte[] prefix_key = StorageKey.CreateSearchPrefix(Id, new[] { Prefix_Candidate });
     return(snapshot.Storages.Find(prefix_key).Select(p =>
                                                      (
                                                          p.Key.Key.AsSerializable <ECPoint>(1),
                                                          p.Value.GetInteroperable <CandidateState>()
                                                      )).Where(p => p.Item2.Registered).Select(p => (p.Item1, p.Item2.Votes)));
 }
Пример #24
0
        internal bool LoadPolicy(StoreView snapshot)
        {
            _maxTxPerBlock = (int)NativeContract.Policy.GetMaxTransactionsPerBlock(snapshot);
            long newFeePerByte = NativeContract.Policy.GetFeePerByte(snapshot);
            bool policyChanged = newFeePerByte > _feePerByte;

            _feePerByte = newFeePerByte;
            return(policyChanged);
        }
Пример #25
0
        public bool CheckTransaction(Transaction tx, StoreView snapshot)
        {
            BigInteger balance = NativeContract.GAS.BalanceOf(snapshot, tx.Sender);

            senderFee.TryGetValue(tx.Sender, out var totalSenderFeeFromPool);
            BigInteger fee = tx.SystemFee + tx.NetworkFee + totalSenderFeeFromPool;

            return(balance >= fee);
        }
Пример #26
0
        private bool _snapshotChangeHeaderHashIndex(StoreView snapshot, uint index, UInt256 hash)
        {
            HashIndexState hashIndex = snapshot.HeaderHashIndex.GetAndChange();

            hashIndex.Index = index;
            hashIndex.Hash  = hash;

            return(true);
        }
Пример #27
0
 protected ApplicationEngine(TriggerType trigger, IVerifiable container, StoreView snapshot, long gas)
 {
     this.Trigger         = trigger;
     this.ScriptContainer = container;
     this.Snapshot        = snapshot;
     this.gas_amount      = gas;
     this.exec_fee_factor = snapshot is null ? PolicyContract.DefaultExecFeeFactor : NativeContract.Policy.GetExecFeeFactor(Snapshot);
     this.StoragePrice    = snapshot is null ? PolicyContract.DefaultStoragePrice : NativeContract.Policy.GetStoragePrice(Snapshot);
 }
Пример #28
0
 UInt160[] IVerifiable.GetScriptHashesForVerifying(StoreView snapshot)
 {
     ECPoint[] validators = NativeContract.NEO.GetNextBlockValidators(snapshot);
     if (validators.Length <= ValidatorIndex)
     {
         throw new InvalidOperationException();
     }
     return(new[] { Contract.CreateSignatureRedeemScript(validators[ValidatorIndex]).ToScriptHash() });
 }
Пример #29
0
        public uint GetStoragePrice(StoreView snapshot)
        {
            StorageItem item = snapshot.Storages.TryGet(CreateStorageKey(Prefix_StoragePrice));

            if (item is null)
            {
                return(DefaultStoragePrice);
            }
            return((uint)(BigInteger)item);
        }
Пример #30
0
        public uint GetExecFeeFactor(StoreView snapshot)
        {
            StorageItem item = snapshot.Storages.TryGet(CreateStorageKey(Prefix_ExecFeeFactor));

            if (item is null)
            {
                return(DefaultExecFeeFactor);
            }
            return((uint)(BigInteger)item);
        }