public static bool Transfer(UInt160 from, UInt160 to, BigInteger amount, object data) { if (amount <= 0) { throw new Exception("The parameter amount MUST be greater than 0."); } if (!Runtime.CheckWitness(from) && !from.Equals(ExecutionEngine.CallingScriptHash)) { throw new Exception("No authorization."); } if (AssetStorage.Get(from) < amount) { throw new Exception("Insufficient balance."); } if (from == to) { return(true); } AssetStorage.Reduce(from, amount); AssetStorage.Increase(to, amount); OnTransfer(from, to, amount); // Validate payable if (ContractManagement.GetContract(to) != null) { Contract.Call(to, "onNEP17Payment", CallFlags.All, new object[] { from, amount, data }); } return(true); }
/// <inheritdoc /> public IWalletAccount ImportScriptHash(UInt160 scriptHash) { if (scriptHash == null) { throw new ArgumentNullException(); } if (scriptHash.Equals(UInt160.Zero)) { throw new ArgumentException(); } CheckWalletIsOpen(); //TODO #360: Load Contract from persistence? var emptyContractCode = new Code { ScriptHash = scriptHash }; var emptyContract = new Contract { Code = emptyContractCode }; var account = new NEP6Account(emptyContract); AddAccount(account); return(account); }
public LocalNode(ZoroSystem system, UInt160 chainHash) { lock (lockObj) { this.system = system; this.ChainHash = chainHash; if (chainHash.Equals(UInt160.Zero)) { if (root != null) { throw new InvalidOperationException(); } root = this; SeedList = ProtocolSettings.Default.SeedList; } else { AppChainState state = ZoroChainSystem.Singleton.RegisterAppChainLocalNode(chainHash, this); SeedList = state.SeedList; } Blockchain = ZoroChainSystem.Singleton.AskBlockchain(chainHash); } LoadRecentPeers(); }
public static bool Transfer(UInt160 from, UInt160 to, BigInteger amount, object data) { if (!ValidateAddress(from) || !ValidateAddress(to)) { throw new Exception("The parameters from and to SHOULD be 20-byte non-zero addresses."); } if (amount <= 0) { throw new Exception("The parameter amount MUST be greater than 0."); } if (!Runtime.CheckWitness(from) && !from.Equals(ExecutionEngine.CallingScriptHash)) { throw new Exception("No authorization."); } if (AssetStorage.Get(from) < amount) { throw new Exception("Insufficient balance."); } if (from == to) { return(true); } AssetStorage.Reduce(from, amount); AssetStorage.Increase(to, amount); OnTransfer(from, to, amount); // Validate payable if (IsDeployed(to)) { Contract.Call(to, "onPayment", new object[] { from, amount, data }); } return(true); }
public static bool Transfer(UInt160 from, UInt160 to, BigInteger amount) { if (!ValidateAddress(from) || !ValidateAddress(to)) { throw new Exception("The parameters from and to SHOULD be 20-byte non-zero addresses."); } if (amount <= 0) { throw new Exception("The parameter amount MUST be greater than 0."); } if (!IsPayable(to)) { throw new Exception("Receiver cannot receive."); } if (!Runtime.CheckWitness(from) && !from.Equals(ExecutionEngine.CallingScriptHash)) { throw new Exception("No authorization."); } if (AssetStorage.Get(from) < amount) { throw new Exception("Insufficient balance."); } if (from == to) { return(true); } AssetStorage.Reduce(from, amount); AssetStorage.Increase(to, amount); OnTransfer(from, to, amount); return(true); }
// 根链或者应用链被启动 public void OnBlockChainStarted(UInt160 chainHash, int port, int wsport) { // 在根链启动后,获取应用链列表,启动应用链 if (chainHash.Equals(UInt160.Zero) && CheckAppChainPort()) { AddListeningPort(port, wsport); // 获取应用链列表 IEnumerable <AppChainState> appchains = Blockchain.Root.Store.GetAppChains().Find().OrderBy(p => p.Value.Timestamp).Select(p => p.Value); foreach (var state in appchains) { // 判断是否需要运行该应用链 if (ShouldStartAppChain(state)) { // 检查种子节点是否有效 if (CheckSeedList(state)) { StartAppChain(state); } else { Log($"The appchain's seedlist is invalid, name={state.Name} hash={state.Hash}", LogLevel.Warning); } } } } }
public void Can_be_equal_to_another_number_of_object_type() { var a = new UInt160(new byte[] { 212, 41, 126, 177, 14, 255, 59, 82, 218, 113, 248, 145, 98, 5, 128, 140, 42, 70, 32, 69 }); var b = (object)UInt160.Parse("0x4520462a8c80056291f871da523bff0eb17e29d4"); a.Equals(b).Should().BeTrue(); }
public static bool TransferFrom(Snapshot snapshot, UInt160 assetId, UInt160 from, UInt160 to, Fixed8 amount) { BigInteger value = new BigInteger(amount.GetData()); if (value <= 0) { return(false); } if (from.Equals(to)) { return(false); } if (from.ToArray().Length != 20 || to.ToArray().Length != 20) { return(false); } var keyFrom = new byte[] { 0x11 }.Concat(from.ToArray()).ToArray(); BigInteger from_value = StorageGet(snapshot, assetId, keyFrom).AsBigInteger(); var keyApprove = from.ToArray().Concat(to.ToArray()).ToArray(); BigInteger approve_value = StorageGet(snapshot, assetId, keyApprove).AsBigInteger(); if (from_value < value || approve_value < value) { return(false); } //update Allowance if (approve_value == value) { StorageDelete(snapshot, assetId, keyApprove); } else { StoragePut(snapshot, assetId, keyApprove, approve_value - value); } //update from balance if (from_value == value) { StorageDelete(snapshot, assetId, keyFrom); } else { StoragePut(snapshot, assetId, keyFrom, from_value - value); } //update to balance var keyTo = new byte[] { 0x11 }.Concat(to.ToArray()).ToArray(); BigInteger to_value = StorageGet(snapshot, assetId, keyTo).AsBigInteger(); StoragePut(snapshot, assetId, keyTo, to_value + value); return(true); }
public void Can_TryParse() { UInt160 a = new UInt160(0x0807060504030201, 0x100f0e0d0c0b0a09, 0x14131211); const string @string = "0x14131211100f0e0d0c0b0a090807060504030201"; UInt160.TryParse(@string, out var b).Should().BeTrue(); a.Equals(b).Should().BeTrue(); }
/// <summary> /// Make and send transaction with script, sender /// </summary> /// <param name="script">script</param> /// <param name="account">sender</param> private void SendTransaction(byte[] script, UInt160 account = null) { List <Cosigner> signCollection = new List <Cosigner>(); if (account != null) { using (SnapshotView snapshot = Blockchain.Singleton.GetSnapshot()) { UInt160[] accounts = CurrentWallet.GetAccounts().Where(p => !p.Lock && !p.WatchOnly).Select(p => p.ScriptHash).Where(p => NativeContract.GAS.BalanceOf(snapshot, p).Sign > 0).ToArray(); foreach (var signAccount in accounts) { if (account.Equals(signAccount)) { signCollection.Add(new Cosigner() { Account = signAccount }); break; } } } } try { Transaction tx = CurrentWallet.MakeTransaction(script, account, signCollection?.ToArray()); Console.WriteLine($"Invoking script with: '{tx.Script.ToHexString()}'"); using (ApplicationEngine engine = ApplicationEngine.Run(tx.Script, tx, null, testMode: true)) { Console.WriteLine($"VM State: {engine.State}"); Console.WriteLine($"Gas Consumed: {new BigDecimal(engine.GasConsumed, NativeContract.GAS.Decimals)}"); Console.WriteLine($"Evaluation Stack: {new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson()))}"); Console.WriteLine(); if (engine.State.HasFlag(VMState.FAULT)) { Console.WriteLine("Engine faulted."); return; } } if (!ReadUserInput("relay tx(no|yes)").IsYes()) { return; } SignAndSendTx(tx); } catch (InvalidOperationException) { Console.WriteLine("Error: insufficient balance."); return; } return; }
public NEP5AssetItem GetNEP5Asset(UInt160 scriptHash) { if (scriptHash == null) { return(null); } return(this.assets.FirstOrDefault(asset => asset is NEP5AssetItem && scriptHash.Equals(((NEP5AssetItem)asset).ScriptHash)) as NEP5AssetItem); }
public void TestEquals() { byte[] temp = new byte[20]; temp[19] = 0x01; UInt160 result = new UInt160(temp); Assert.AreEqual(true, UInt160.Zero.Equals(UInt160.Zero)); Assert.AreEqual(false, UInt160.Zero.Equals(result)); Assert.AreEqual(false, result.Equals(null)); }
protected virtual bool Transfer(ApplicationEngine engine, UInt160 from, UInt160 to, BigInteger amount, StackItem data) { if (amount.Sign < 0) throw new ArgumentOutOfRangeException(nameof(amount)); if (!from.Equals(engine.CallingScriptHash) && !engine.CheckWitnessInternal(from)) return false; StorageKey key_from = CreateStorageKey(Prefix_Account).Add(from); StorageItem storage_from = engine.Snapshot.GetAndChange(key_from); if (amount.IsZero) { if (storage_from != null) { TState state_from = storage_from.GetInteroperable<TState>(); OnBalanceChanging(engine, from, state_from, amount); } } else { if (storage_from is null) return false; TState state_from = storage_from.GetInteroperable<TState>(); if (state_from.Balance < amount) return false; if (from.Equals(to)) { OnBalanceChanging(engine, from, state_from, BigInteger.Zero); } else { OnBalanceChanging(engine, from, state_from, -amount); if (state_from.Balance == amount) engine.Snapshot.Delete(key_from); else state_from.Balance -= amount; StorageKey key_to = CreateStorageKey(Prefix_Account).Add(to); StorageItem storage_to = engine.Snapshot.GetAndChange(key_to, () => new StorageItem(new TState())); TState state_to = storage_to.GetInteroperable<TState>(); OnBalanceChanging(engine, to, state_to, amount); state_to.Balance += amount; } } PostTransfer(engine, from, to, amount, data, true); return true; }
public bool Equals(Contract other) { if (ReferenceEquals(this, other)) { return(true); } if (ReferenceEquals(null, other)) { return(false); } return(ScriptHash.Equals(other.ScriptHash)); }
public bool Equals(StorageKey other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(ScriptHash.Equals(other.ScriptHash) && MemoryExtensions.SequenceEqual <byte>(Key, other.Key)); }
private WalletAccount GetWalletAccount(UInt160 scriptHash) { if (scriptHash == null) { return(null); } this.ThrowIfWalletIsNotOpen(); return(this.GetAccounts().FirstOrDefault(account => scriptHash.Equals(account.ScriptHash))); }
public static LocalNode GetLocalNode(UInt160 chainHash) { if (!chainHash.Equals(UInt160.Zero)) { appnodes.TryGetValue(chainHash, out LocalNode localNode); return(localNode); } else { return(Root); } }
public bool Equals(Nep5BalanceKey other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(UserScriptHash.Equals(other.UserScriptHash) && AssetScriptHash.Equals(AssetScriptHash)); }
public static Blockchain GetBlockchain(UInt160 chainHash) { if (!chainHash.Equals(UInt160.Zero)) { appchains.TryGetValue(chainHash, out Blockchain blockchain); return(blockchain); } else { return(Root); } }
public bool Equals(StorageKey other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(ScriptHash.Equals(other.ScriptHash) && Key.SequenceEqual(other.Key)); }
public bool Equals(Nep11BalanceKey other) { if (other is null) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(UserScriptHash.Equals(other.UserScriptHash) && AssetScriptHash.Equals(AssetScriptHash) && Token.Equals(other.Token)); }
public bool Equals(KeyPair other) { if (ReferenceEquals(this, other)) { return(true); } if (ReferenceEquals(null, other)) { return(false); } return(PublicKeyHash.Equals(other.PublicKeyHash)); }
/// <summary> /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hash">The hash of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) return true; if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute<OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) return false; if (signer.Scopes == WitnessScope.Global) return true; if (signer.Scopes.HasFlag(WitnessScope.CalledByEntry)) { if (CallingScriptHash == null || CallingScriptHash == EntryScriptHash) return true; } if (signer.Scopes.HasFlag(WitnessScope.CustomContracts)) { if (signer.AllowedContracts.Contains(CurrentScriptHash)) return true; } if (signer.Scopes.HasFlag(WitnessScope.CustomGroups)) { // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); var contract = NativeContract.ContractManagement.GetContract(Snapshot, CallingScriptHash); // check if current group is the required one if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(signer.AllowedGroups).Any()) return true; } return false; } // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return hashes_for_verifying.Contains(hash); }
public bool Equals(StorageKey other) { TR.Enter(); if (ReferenceEquals(other, null)) { return(TR.Exit(false)); } if (ReferenceEquals(this, other)) { return(TR.Exit(true)); } return(TR.Exit(ScriptHash.Equals(other.ScriptHash) && Key.SequenceEqual(other.Key))); }
public Account FindAccountByHash(UInt160 hash) { foreach (var entry in _accounts) { var bytes = CryptoUtils.AddressToScriptHash(entry.keys.address); var temp = new UInt160(bytes); if (temp.Equals(hash)) { return(entry); } } return(null); }
public bool Equals(Nep17TransferKey other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return(UserScriptHash.Equals(other.UserScriptHash) && TimestampMS.Equals(other.TimestampMS) && AssetScriptHash.Equals(other.AssetScriptHash) && BlockXferNotificationIndex.Equals(other.BlockXferNotificationIndex)); }
private void UpdateResultFromFile(UInt160 hash) { var path = this.GetCachedCertificatePathFromScriptHash(hash); X509Certificate2 cert; try { cert = new X509Certificate2(path); } catch (CryptographicException) { results[hash].Type = CertificateQueryResultType.Missing; return; } if (cert.PublicKey.Oid.Value != "1.2.840.10045.2.1") { results[hash].Type = CertificateQueryResultType.Missing; return; } // Compare hash with cached value var decodedPublicKey = ECPoint.DecodePoint(cert.PublicKey.EncodedKeyValue.RawData, ECCurve.Secp256r1); var decodedHash = GetRedeemScriptHashFromPublicKey(decodedPublicKey); if (!hash.Equals(decodedHash)) { results[hash].Type = CertificateQueryResultType.Missing; return; } using (var chain = new X509Chain()) { results[hash].Certificate = cert; if (chain.Build(cert)) { results[hash].Type = CertificateQueryResultType.Good; } else if (chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.NotTimeValid) { results[hash].Type = CertificateQueryResultType.Expired; } else { results[hash].Type = CertificateQueryResultType.Invalid; } } }
/// <summary> /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hash">The hash of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) { return(true); } if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) { return(false); } foreach (WitnessRule rule in signer.GetAllRules()) { if (rule.Condition.Match(this)) { return(rule.Action == WitnessRuleAction.Allow); } } return(false); } // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return(hashes_for_verifying.Contains(hash)); }
public static bool Migrate(UInt160 script, string manifest) { if (!IsPaused()) { Error("System is not paused."); return(false); } if (!IsAdmin()) { Error("No authorization."); return(false); } if (script != null && script.Equals(ContractManagement.GetContract(Runtime.ExecutingScriptHash))) { return(true); } ContractManagement.Update(script, manifest); return(true); }
private static void UpdateResultFromFile(UInt160 hash) { string address = hash.ToAddress(); X509Certificate2 cert; try { cert = new X509Certificate2(Path.Combine(Settings.Default.Paths.CertCache, $"{address}.cer")); } catch (CryptographicException) { results[hash].Type = CertificateQueryResultType.Missing; return; } if (cert.PublicKey.Oid.Value != "1.2.840.10045.2.1") { results[hash].Type = CertificateQueryResultType.Missing; return; } if (!hash.Equals(Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(cert.PublicKey.EncodedKeyValue.RawData, ECCurve.Secp256r1)).ToScriptHash())) { results[hash].Type = CertificateQueryResultType.Missing; return; } using (X509Chain chain = new X509Chain()) { results[hash].Certificate = cert; if (chain.Build(cert)) { results[hash].Type = CertificateQueryResultType.Good; } else if (chain.ChainStatus.Length == 1 && chain.ChainStatus[0].Status == X509ChainStatusFlags.NotTimeValid) { results[hash].Type = CertificateQueryResultType.Expired; } else { results[hash].Type = CertificateQueryResultType.Invalid; } } }